<template>
  <div class="dashboard-container">
    <!-- 用户问候与天气信息 -->
    <el-card shadow="never" class="mt-2">
      <div class="flex flex-wrap">
        <div class="flex-1 flex items-start">
          <img
            class="w80px h80px rounded-full"
            :src="userStore.userInfo.avatar + '?imageView2/1/w/80/h/80'"
          />
          <div class="ml-5">
            <p>{{ greetings }} {{ today }}</p>
            <p class="text-sm text-gray">
              今日天气：{{ weatherData.weather }}，气温：{{ weatherData.temperature }}℃，风向：{{
                weatherData.windDirection
              }}，风力：{{ weatherData.windScale }}，地区：{{ weatherData.place }}。
            </p>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 数据统计 -->
    <el-row :gutter="10" class="mt-5">
      <!-- 在线用户数量 -->
      <el-col :span="8" :xs="24" class="mb-xs-3">
        <el-card shadow="never" class="h-full flex flex-col">
          <template #header>
            <div class="flex-x-between">
              <span class="text-gray">在线用户</span>
              <el-tag type="danger" size="small">实时</el-tag>
            </div>
          </template>

          <div class="flex-x-between mt-2 flex-1">
            <div class="flex-y-center">
              <span class="text-lg transition-all duration-300 hover:scale-110">
                {{ onlineUserCount }}
              </span>
              <span v-if="onlineCountIsConnected" class="ml-2 text-xs text-[#67c23a]">
                <el-icon><Connection /></el-icon>
                已连接
              </span>
              <span v-else class="ml-2 text-xs text-[#f56c6c]">
                <el-icon><Failed /></el-icon>
                未连接
              </span>
            </div>
            <div class="i-svg:people w-8 h-8 animate-[pulse_2s_infinite]" />
          </div>

          <div class="flex-x-between mt-2 text-sm text-gray">
            <span>更新时间</span>
            <span>{{ formattedTime }}</span>
          </div>
        </el-card>
      </el-col>

      <!-- 访客数(UV) -->
      <el-col :span="8" :xs="24" class="mb-xs-3">
        <el-skeleton :loading="visitStatsLoading" :rows="5" animated>
          <template #template>
            <el-card>
              <template #header>
                <div>
                  <el-skeleton-item variant="h3" style="width: 40%" />
                  <el-skeleton-item variant="rect" style="float: right; width: 1em; height: 1em" />
                </div>
              </template>

              <div class="flex-x-between">
                <el-skeleton-item variant="text" style="width: 30%" />
                <el-skeleton-item variant="circle" style="width: 2em; height: 2em" />
              </div>
              <div class="mt-5 flex-x-between">
                <el-skeleton-item variant="text" style="width: 50%" />
                <el-skeleton-item variant="text" style="width: 1em" />
              </div>
            </el-card>
          </template>
          <template v-if="!visitStatsLoading">
            <el-card shadow="never" class="h-full flex flex-col">
              <template #header>
                <div class="flex-x-between">
                  <span class="text-gray">访客数(UV)</span>
                  <el-tag type="success" size="small">日</el-tag>
                </div>
              </template>

              <div class="flex-x-between mt-2 flex-1">
                <div class="flex-y-center">
                  <span class="text-lg">{{ Math.round(transitionUvCount) }}</span>
                  <span
                    :class="[
                      'text-xs',
                      'ml-2',
                      computeGrowthRateClass(visitStatsData.uvGrowthRate),
                    ]"
                  >
                    <el-icon>
                      <Top v-if="visitStatsData.uvGrowthRate > 0" />
                      <Bottom v-else-if="visitStatsData.uvGrowthRate < 0" />
                    </el-icon>
                    {{ formatGrowthRate(visitStatsData.uvGrowthRate) }}
                  </span>
                </div>
                <div class="i-svg:visitor w-8 h-8" />
              </div>

              <div class="flex-x-between mt-2 text-sm text-gray">
                <span>总访客数</span>
                <span>{{ Math.round(transitionTotalUvCount) }}</span>
              </div>
            </el-card>
          </template>
        </el-skeleton>
      </el-col>

      <!-- 浏览量(PV) -->
      <el-col :span="8" :xs="24">
        <el-skeleton :loading="visitStatsLoading" :rows="5" animated>
          <template #template>
            <el-card>
              <template #header>
                <div>
                  <el-skeleton-item variant="h3" style="width: 40%" />
                  <el-skeleton-item variant="rect" style="float: right; width: 1em; height: 1em" />
                </div>
              </template>

              <div class="flex-x-between">
                <el-skeleton-item variant="text" style="width: 30%" />
                <el-skeleton-item variant="circle" style="width: 2em; height: 2em" />
              </div>
              <div class="mt-5 flex-x-between">
                <el-skeleton-item variant="text" style="width: 50%" />
                <el-skeleton-item variant="text" style="width: 1em" />
              </div>
            </el-card>
          </template>
          <template v-if="!visitStatsLoading">
            <el-card shadow="never" class="h-full flex flex-col">
              <template #header>
                <div class="flex-x-between">
                  <span class="text-gray">浏览量(PV)</span>
                  <el-tag type="primary" size="small">日</el-tag>
                </div>
              </template>

              <div class="flex-x-between mt-2 flex-1">
                <div class="flex-y-center">
                  <span class="text-lg">{{ Math.round(transitionPvCount) }}</span>
                  <span
                    :class="[
                      'text-xs',
                      'ml-2',
                      computeGrowthRateClass(visitStatsData.pvGrowthRate),
                    ]"
                  >
                    <el-icon>
                      <Top v-if="visitStatsData.pvGrowthRate > 0" />
                      <Bottom v-else-if="visitStatsData.pvGrowthRate < 0" />
                    </el-icon>
                    {{ formatGrowthRate(visitStatsData.pvGrowthRate) }}
                  </span>
                </div>
                <div class="i-svg:browser w-8 h-8" />
              </div>

              <div class="flex-x-between mt-2 text-sm text-gray">
                <span>总浏览量</span>
                <span>{{ Math.round(transitionTotalPvCount) }}</span>
              </div>
            </el-card>
          </template>
        </el-skeleton>
      </el-col>
    </el-row>

    <!-- 系统资源监控 -->
    <el-row :gutter="10" class="mt-5">
      <!-- CPU使用率 -->
      <el-col :span="6" :xs="12" class="mb-xs-3">
        <el-card shadow="never" class="h-full">
          <template #header>
            <div class="flex-x-between">
              <span class="text-gray">CPU使用率</span>
              <el-tag :type="getLevelType(systemStats.cpuUsage)" size="small">
                {{ getLevelText(systemStats.cpuUsage) }}
              </el-tag>
            </div>
          </template>
          <div class="mt-4">
            <el-progress
              :text-inside="true"
              :stroke-width="26"
              :percentage="systemStats.cpuUsage"
              :status="getProgressStatus(systemStats.cpuUsage)"
            />
            <div class="flex-x-between mt-2 text-sm">
              <span>核心数: {{ systemStats.cpuCores }}</span>
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- 内存使用率 -->
      <el-col :span="6" :xs="12" class="mb-xs-3">
        <el-card shadow="never" class="h-full">
          <template #header>
            <div class="flex-x-between">
              <span class="text-gray">内存使用率</span>
              <el-tag :type="getLevelType(systemStats.memoryUsage)" size="small">
                {{ getLevelText(systemStats.memoryUsage) }}
              </el-tag>
            </div>
          </template>
          <div class="mt-4">
            <el-progress
              :text-inside="true"
              :stroke-width="24"
              :percentage="systemStats.memoryUsage"
              :status="getProgressStatus(systemStats.memoryUsage)"
            />
            <div class="flex-x-between mt-2 text-sm">
              <span>已用: {{ formatBytes(systemStats.memoryUsed) }}</span>
              <span>总计: {{ formatBytes(systemStats.memoryTotal) }}</span>
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- 磁盘使用率 -->
      <el-col :span="6" :xs="12" class="mb-xs-3">
        <el-card shadow="never" class="h-full">
          <template #header>
            <div class="flex-x-between">
              <span class="text-gray">磁盘使用率</span>
              <el-tag :type="getLevelType(systemStats.diskUsage)" size="small">
                {{ getLevelText(systemStats.diskUsage) }}
              </el-tag>
            </div>
          </template>
          <div class="mt-4">
            <el-progress
              :text-inside="true"
              :stroke-width="22"
              :percentage="systemStats.diskUsage"
              :status="getProgressStatus(systemStats.diskUsage)"
            />
            <div class="flex-x-between mt-2 text-sm">
              <span>已用: {{ formatBytes(systemStats.diskUsed) }}</span>
              <span>总计: {{ formatBytes(systemStats.diskTotal) }}</span>
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- 网络状态 -->
      <el-col :span="6" :xs="12">
        <el-card shadow="never" class="h-full">
          <template #header>
            <div class="flex-x-between">
              <span class="text-gray">网络状态</span>
              <el-tag v-if="systemStats.networkConnected" type="success" size="small">
                已连接
              </el-tag>
              <el-tag v-else type="danger" size="small">断开连接</el-tag>
            </div>
          </template>
          <div class="mt-2">
            <div class="flex-x-between items-center mb-2">
              <span class="text-sm">上传速度</span>
              <span class="text-sm font-medium">{{ formatSpeed(systemStats.networkUpload) }}</span>
            </div>
            <div class="flex-x-between items-center">
              <span class="text-sm">下载速度</span>
              <span class="text-sm font-medium">
                {{ formatSpeed(systemStats.networkDownload) }}
              </span>
            </div>
            <div class="mt-4 flex justify-center">
              <div class="w-16 h-16 relative">
                <svg class="w-full h-full" viewBox="0 0 100 100">
                  <!-- 上传箭头 -->
                  <path d="M30,60 L50,30 L70,60" stroke="#409EFF" stroke-width="4" fill="none" />
                  <path d="M30,60 L70,60" stroke="#409EFF" stroke-width="4" fill="none" />
                  <!-- 下载箭头 -->
                  <path d="M30,40 L50,70 L70,40" stroke="#67C23A" stroke-width="4" fill="none" />
                  <path d="M30,40 L70,40" stroke="#67C23A" stroke-width="4" fill="none" />
                </svg>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 访问趋势统计图 -->
    <el-row :gutter="10" class="mt-5">
      <el-col :xs="24" :span="24">
        <el-card>
          <template #header>
            <div class="flex-x-between">
              <span>访问趋势</span>
              <el-radio-group v-model="visitTrendDateRange" size="small">
                <el-radio-button :value="7">近7天</el-radio-button>
                <el-radio-button :value="30">近30天</el-radio-button>
              </el-radio-group>
            </div>
          </template>
          <ECharts :options="visitTrendChartOptions" height="350px" />
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, ref, watch } from "vue";
import { dayjs, ElMessage } from "element-plus";
import { useDateFormat, useTransition } from "@vueuse/core";
import { Bottom, Connection, Failed, Top } from "@element-plus/icons-vue";

import { useUserStore } from "@/store/modules/user.store";
import { formatGrowthRate } from "@/utils";
import { computeGrowthRateClass } from "@/api/dashboard/dashboard.api";
import { useOnlineCount } from "@/composables/useOnlineCount";
import { useSystemMonitor } from "@/composables/useSystemMonitor";
import LogAPI, { VisitStatsVO, VisitTrendVO } from "@/api/system/log.api";

// 在线用户数量
const { onlineUserCount, lastUpdateTime, isConnected: onlineCountIsConnected } = useOnlineCount();
const previousCount = ref(0);
const today = new Date().toISOString().slice(0, 10);

// 监听在线用户数量变化
watch(onlineUserCount, (newCount, oldCount) => {
  if (oldCount > 0) {
    previousCount.value = oldCount;
  }
});

// 格式化最后更新时间
const formattedTime = computed(() => {
  if (!lastUpdateTime.value) return "--";
  return useDateFormat(lastUpdateTime, "HH:mm:ss").value;
});

// 系统资源监控
const { systemStats, isConnected } = useSystemMonitor();

// 监听连接状态变化
watch(isConnected, (connected) => {
  if (!connected) {
    ElMessage.warning({
      message: "系统监控连接已断开",
      type: "warning",
      duration: 5000, // 显示5秒
    });
  } else {
    // 可选：连接恢复时显示成功消息
    ElMessage.success("系统监控连接已恢复");
  }
});

// 系统资源监控相关方法
const getLevelType = (value: number) => {
  if (value < 30) return "success";
  if (value < 70) return "warning";
  return "danger";
};

const getLevelText = (value: number) => {
  if (value < 30) return "正常";
  if (value < 70) return "中等";
  return "紧张";
};

const getProgressStatus = (value: number | string | undefined) => {
  // 处理非数值情况
  if (value === undefined || value === null) return undefined;

  // 转换为数字并检查是否为有效数值
  const numValue = Number(value);
  if (isNaN(numValue)) return undefined;

  // 返回状态
  return numValue >= 70 ? "exception" : undefined;
};

const formatBytes = (bytes: number) => {
  if (bytes === 0) return "0 B";
  const k = 1024;
  const sizes = ["B", "KB", "MB", "GB", "TB"];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + " " + sizes[i];
};

const formatSpeed = (bytes: number) => {
  if (bytes < 1024) return bytes + " B/s";
  if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(2) + " KB/s";
  return (bytes / (1024 * 1024)).toFixed(2) + " MB/s";
};

// 用户信息和问候语
const userStore = useUserStore();
const currentDate = new Date();
const greetings = computed(() => {
  const hours = currentDate.getHours();
  const nickname = userStore.userInfo.nickname || "用户";
  if (hours >= 6 && hours < 8) {
    return "晨起披衣出草堂，轩窗已自喜微凉🌅！";
  } else if (hours >= 8 && hours < 12) {
    return `上午好，${nickname}！`;
  } else if (hours >= 12 && hours < 18) {
    return `下午好，${nickname}！`;
  } else if (hours >= 18 && hours < 24) {
    return `晚上好，${nickname}！`;
  } else {
    return "偷偷向银河要了一把碎星，只等你闭上眼睛撒入你的梦中，晚安🌛！";
  }
});

// 天气数据
const weatherData = ref({
  temperature: 0,
  weather: "未知",
  windDirection: "未知",
  windScale: "未知",
  place: "未知",
});

const fetchWeatherData = async () => {
  const apiUrl =
    "https://cn.apihz.cn/api/tianqi/tqyb.php?id=10004830&key=ce5d6e31e71464c30887fdfa3804224c&sheng=内蒙古&place=呼和浩特";
  try {
    const response = await fetch(apiUrl);
    if (!response.ok) throw new Error("天气数据请求失败");
    const data = await response.json();
    weatherData.value = {
      temperature: data.temperature,
      weather: data.weather1,
      windDirection: data.windDirection,
      windScale: data.windScale,
      place: data.place,
    };
  } catch (error) {
    console.error("Failed to fetch weather data:", error);
  }
};

// 访客统计数据
const visitStatsLoading = ref(true);
const visitStatsData = ref<VisitStatsVO>({
  todayUvCount: 0,
  uvGrowthRate: 0,
  totalUvCount: 0,
  todayPvCount: 0,
  pvGrowthRate: 0,
  totalPvCount: 0,
});

const transitionUvCount = useTransition(
  computed(() => visitStatsData.value.todayUvCount),
  { duration: 1000, transition: [0.25, 0.1, 0.25, 1.0] }
);

const transitionTotalUvCount = useTransition(
  computed(() => visitStatsData.value.totalUvCount),
  { duration: 1200, transition: [0.25, 0.1, 0.25, 1.0] }
);

const transitionPvCount = useTransition(
  computed(() => visitStatsData.value.todayPvCount),
  { duration: 1000, transition: [0.25, 0.1, 0.25, 1.0] }
);

const transitionTotalPvCount = useTransition(
  computed(() => visitStatsData.value.totalPvCount),
  { duration: 1200, transition: [0.25, 0.1, 0.25, 1.0] }
);

// 访问趋势图表
const visitTrendDateRange = ref(7);
const visitTrendChartOptions = ref();

const fetchVisitStatsData = () => {
  LogAPI.getVisitStats()
    .then((data) => {
      visitStatsData.value = data;
    })
    .finally(() => {
      visitStatsLoading.value = false;
    });
};

const fetchVisitTrendData = () => {
  const startDate = dayjs()
    .subtract(visitTrendDateRange.value - 1, "day")
    .format("YYYY-MM-DD");
  const endDate = dayjs().format("YYYY-MM-DD");

  LogAPI.getVisitTrend({ startDate, endDate }).then((data) => {
    updateVisitTrendChartOptions(data);
  });
};

const updateVisitTrendChartOptions = (data: VisitTrendVO) => {
  visitTrendChartOptions.value = {
    tooltip: { trigger: "axis" },
    legend: { data: ["浏览量(PV)", "访客数(UV)"], bottom: 0 },
    grid: { left: "1%", right: "5%", bottom: "10%", containLabel: true },
    xAxis: { type: "category", data: data.dates },
    yAxis: { type: "value", splitLine: { show: true, lineStyle: { type: "dashed" } } },
    series: [
      {
        name: "浏览量(PV)",
        type: "line",
        data: data.pvList,
        areaStyle: { color: "rgba(64, 158, 255, 0.1)" },
        smooth: true,
        itemStyle: { color: "#4080FF" },
        lineStyle: { color: "#4080FF" },
      },
      {
        name: "访客数(UV)",
        type: "line",
        data: data.ipList,
        areaStyle: { color: "rgba(103, 194, 58, 0.1)" },
        smooth: true,
        itemStyle: { color: "#67C23A" },
        lineStyle: { color: "#67C23A" },
      },
    ],
  };
};

watch(visitTrendDateRange, fetchVisitTrendData, { immediate: true });

// 组件挂载时初始化数据和WebSocket连接
onMounted(() => {
  // 手动触发连接
  fetchWeatherData();
  fetchVisitStatsData();

  // 从 useSystemMonitor 返回值中获取 isConnected 和 isConnecting
  const { isConnected, isConnecting, initWebSocket } = useSystemMonitor();
  if (!isConnected.value && !isConnecting.value) {
    initWebSocket();
  }
});
</script>

<style lang="scss" scoped>
@use "@/styles/dashboard";

// 系统监控进度条样式
.el-progress--line {
  max-width: 600px;
  margin-bottom: 15px;
}

// 调整进度条文本样式
:deep(.el-progress__text) {
  font-size: 14px;
  font-weight: bold;
}
</style>
